package cn.smbms.controller;

import cn.smbms.dao.provider.ProviderMapper;
import cn.smbms.pojo.Provider;
import cn.smbms.service.provider.ProviderService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/provider")
public class ProviderController {
    @Resource
    private ProviderService providerService;

    @RequestMapping("/providerlist.html")
    public String providerList(Model model,
                               @RequestParam(value = "proCode",required = false) String queryProCode,
                               @RequestParam(value = "proName",required = false)  String queryProName,
                               @RequestParam(value = "pageIndex",required = false)  String pageIndex){
        List<Provider> providerList = null;
        //设置页面容量
        int pageSize = Constants.pageSize;
        //当前页码
        int currentPageNo = 1;
        if (queryProCode == null){
            queryProCode = "";
        }
        if (queryProName == null){
            queryProName = "";
        }
        if (pageIndex != null){
            try {
                currentPageNo = Integer.valueOf(pageIndex);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                return "redirect:/user/syserror.html";
            }
        }
        //总数量
        int totalCount = providerService.getProviderCount();
        //总页数
        PageSupport pages = new PageSupport();
        pages.setCurrentPageNo(currentPageNo);
        pages.setPageSize(pageSize);
        pages.setTotalCount(totalCount);

        int totalPageCount = pages.getTotalPageCount();
        //控制首页和尾页
        if (currentPageNo < 1){
            currentPageNo = 1;
        }else if (currentPageNo > totalPageCount){
            currentPageNo = totalPageCount;
        }
        providerList = providerService.getProviderList(queryProCode,queryProName,currentPageNo,pageSize);
        model.addAttribute("providerList",providerList);
        model.addAttribute("queryProCode",queryProCode
        );
        model.addAttribute("queryProName",queryProName);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",totalCount);
        model.addAttribute("currentPageNo",currentPageNo);
        return "providerlist";
    }
}
